﻿using Barcode_Project.Entity;
using Barcode_Project.Local;
using Barcode_Project.Network;
using DevExpress.XtraBars.Alerter;
using DevExpress.XtraEditors;
using log4net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.HSSF.Record;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Barcode_Project.InitPrint
{
    public partial class InWarehousePrint : DevExpress.XtraEditors.XtraForm
    {
        HttpAgreement http;
        ILog _log;
        Dictionary<string, string> datas;
        public InWarehousePrint(Dictionary<string, string> pars)
        {
            datas = pars;
            _log = LogManager.GetLogger(GetType().Name);
            http = new HttpAgreement();

            InitializeComponent();

            new ComputerTask().LoadWarehouse(select_warehouse);
            new ComputerTask().LoadPrinter(select_printer);
            new ComputerTask().LoadTemplate(select_template);
        }

        // 点击搜索存货的按钮
        private void buttonEdit1_Properties_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var win = new ProductSelector();
            var result = win.ShowDialog();

            if (result == DialogResult.OK)
            {
                input_proCode.Text = win.selectedProduct.proCode;
                input_spec.Text = win.selectedProduct.spec;
                input_proName.Text = win.selectedProduct.proName;
                input_unit.Text = win.selectedProduct.proUnit;
            }
        }

        //选择供应商
        private void input_vendorName_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var sel = new VendorSelector();
            var result = sel.ShowDialog();

            if (result == DialogResult.OK)
            {
                input_cu_vendor.Text = sel.selectedVendor.cuCode;
                input_vendorName.Text = sel.selectedVendor.cuName;
            }
        }

        private void button_exit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Application.Exit();
        }
        // 开始打印
        private void button_print_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (!this.button_print.Enabled)
                {
                    return;
                }

                this.button_print.Enabled = false;

                if (!CheckBeforePrint())
                {
                    this.button_print.Enabled = true;
                    return;
                }

                var uploadDic = new Dictionary<string, string>();
                CommonMethods.SetParameterValue(ref uploadDic, group_data.Controls, "input_");
                uploadDic["printNumber"] = input_printNumber.EditValue.ToString();
                uploadDic["userCode"] = WebsiteInfo.userCode;
                uploadDic["houseCode"] = select_warehouse.EditValue.ToString();
                uploadDic["barType"] = "QC";
                if (string.IsNullOrEmpty(input_cu_vendor.Text))
                {
                    uploadDic["cu_vendor"] = "";
                }
                var json = JsonConvert.SerializeObject(uploadDic);

                string url = CommonMethods.APIUrl() + "SaveBarCode";
                var info = http.HttpPost(url, json);

                if (string.IsNullOrWhiteSpace(info))
                {
                    XtraMessageBox.Show("接口返回信息为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.button_print.Enabled = true;
                    return;
                }

                var obj = JsonConvert.DeserializeObject<JObject>(info);

                if (bool.Parse(obj["result"].ToString()))
                {
                    CommonMethods.SetParameterValue(ref datas, this.group_data.Controls, "input_");
                    if (input_unit.Text == "千克")
                    {
                        datas["number"] = input_proWeight.Text;
                    }
                    else
                    {
                        datas["number"] = input_proMeter.Text;
                    }
                    datas["unitName"] = input_unit.Text;

                    //字段重命名
                    datas["cInvName"] = input_proName.Text;
                    datas["cInvStd"] = input_spec.Text;
                    datas["cBatch"] = input_cu_batch.Text;
                    datas["cVenName"] = input_vendorName.Text;


                    var table = CommonMethods.CreatePrintTableByDictionary(datas, obj["data"].ToString());

                    var printerName = ((ItemSelector)select_printer.GetSelectedDataRow()).code;
                    var templatePath = ((ItemSelector)select_template.GetSelectedDataRow()).code;//模板路径

                    new ComputerTask().StartPrintingTask(table, printerName, templatePath);

                }
                else
                {
                    XtraMessageBox.Show(obj["message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.button_print.Enabled = true;
                    return;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.button_print.Enabled = true;
                return;
            }

            this.button_print.Enabled = true;
        }
        /// <summary>
        /// 打印之前，检查必填项
        /// </summary>
        /// <returns></returns>
        bool CheckBeforePrint()
        {
            var result = false;

            if (string.IsNullOrEmpty(input_proCode.Text))
            {
                XtraMessageBox.Show("请选择存货");
                return result;
            }
            if (string.IsNullOrEmpty(input_cu_iUnitCost.Text) || decimal.Parse(input_cu_iUnitCost.Text) == 0.0m )
            {
                XtraMessageBox.Show("请录入单价");
                return result;
            }
            if (string.IsNullOrEmpty(input_proWeight.Text) || decimal.Parse(input_proWeight.Text) == 0.0m)
            {
                XtraMessageBox.Show("请录入重量");
                return result;
            }
            if (string.IsNullOrEmpty(input_proMeter.Text) || decimal.Parse(input_proMeter.Text) == 0.0m)
            {
                XtraMessageBox.Show("请录入米数");
                return result;
            }
            if (decimal.Parse(input_proWeight.Text) == 0.0m && decimal.Parse(input_proMeter.Text) == 0.0m)
            {
                XtraMessageBox.Show("米数/个数与重量不能同时为零");
                return result;
            }
            if (select_warehouse.GetSelectedDataRow() == null)
            {
                XtraMessageBox.Show("请选择仓库");
                return result;
            }
            if (select_printer.GetSelectedDataRow() == null)
            {
                XtraMessageBox.Show("请选择打印机");
                return result;
            }
            if (select_template.GetSelectedDataRow() == null)
            {
                XtraMessageBox.Show("请选择打印模板");
                return result;
            }

            result = true;
            return result;
        }

        /// <summary>
        /// 组织数据
        /// </summary>
        /// <returns></returns>
        string CollectData()
        {
            var data = new Interface_InitPrint
            {
                proCode = input_proCode.Text,
                weight = input_proWeight.Text,
                houseCode = ((ItemSelector)select_warehouse.GetSelectedDataRow()).code,
                printNumber = input_printNumber.Text,

                proName = input_proName.Text,
                spec = input_spec.Text,
            };

            return JsonConvert.SerializeObject(data);
        }

        private void btn_update_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var r = XtraMessageBox.Show("即将关闭程序进行升级，是否继续？", "提示", MessageBoxButtons.OKCancel);
            if (r == DialogResult.OK)
            {
                new RemoteRequest().UpdateCmdProgram();
            }
        }

        private void InWarehousePrint_Load(object sender, EventArgs e)
        {
            input_happenDate.EditValue = DateTime.Now.ToString("yyyy-MM-dd");
        }
    }
}